import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:mall/core/models/address.dart';
import 'package:mall/core/models/address_list.dart';
import 'package:mall/core/providers/pages/mine/address/address_delete_model.dart';
import 'package:mall/core/providers/pages/mine/address/address_list_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/services/new_api.dart';
import 'package:mall/screens/address/address_edit_page.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class AddressPage extends StatelessWidget {
  static const routeName = '/AddressPage';
  final bool args;

  AddressPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => AddressListModel(context.read<NewApi>(), args)),
        ChangeNotifierProvider(create: (context) => AddressDeleteModel(context.read<Api>())),
      ],
      child: Consumer<AddressListModel>(
        builder: (context, value, child) {
          switch (value.viewState) {
            case ViewState.busy:
              return Scaffold(
                appBar: AppBar(
                  title: Text('收货地址'),
                ),
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            case ViewState.error:
              return Scaffold(
                appBar: AppBar(
                  title: Text('收货地址'),
                  actions: [
                    IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        _pushAddressEditPage(context, value.addressList.needVerifyCode, null);
                      },
                    ),
                  ],
                ),
                body: Center(
                  child: Text(value.errorMessage),
                ),
              );
            case ViewState.success:
              return Scaffold(
                appBar: AppBar(
                  title: Text('收货地址'),
                  actions: [
                    IconButton(
                      icon: Icon(Icons.add),
                      onPressed: () {
                        _pushAddressEditPage(context, value.addressList.needVerifyCode, null);
                      },
                    ),
                  ],
                ),
                body: _AddressListWidget(
                  list: value.addressList,
                ),
              );
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _AddressListWidget extends StatelessWidget {
  final AddressList list;

  const _AddressListWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Address> defaultList = [];
    List<Address> normalList = [];
    list.addressItems.forEach(
      (value) {
        if (value.defaulted) {
          defaultList.add(value);
        } else {
          normalList.add(value);
        }
      },
    );
    return CustomScrollView(
      slivers: [
        SliverPadding(
          padding: EdgeInsets.symmetric(vertical: 8.w),
          sliver: SliverFixedExtentList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                Address address = defaultList[index];
                return _AddressItemDefaultWidget(
                  needVerifyCode: list.needVerifyCode,
                  address: address,
                );
              },
              childCount: defaultList.length,
            ),
            itemExtent: 85,
          ),
        ),
        SliverPadding(
          padding: EdgeInsets.symmetric(vertical: 8.w),
          sliver: SliverFixedExtentList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                Address address = normalList[index];
                return _AddressItemNormalWidget(
                  needVerifyCode: list.needVerifyCode,
                  address: address,
                  header: index == 0,
                  footer: index == normalList.length - 1,
                );
              },
              childCount: normalList.length,
            ),
            itemExtent: 85,
          ),
        ),
      ],
    );
  }
}

class _AddressItemDefaultWidget extends StatelessWidget {
  final bool needVerifyCode;
  final Address address;

  const _AddressItemDefaultWidget({
    Key key,
    @required this.needVerifyCode,
    @required this.address,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      child: Row(
        children: <Widget>[
          Container(
            margin: EdgeInsets.symmetric(horizontal: 12),
            child: Image.asset('assets/images/order/ic_location.png', width: 16),
          ),
          Expanded(
            child: GestureDetector(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text.rich(
                    TextSpan(
                      text: address.linkMan,
                      style: TextStyle(fontSize: 16),
                      children: [
                        TextSpan(text: '  '),
                        TextSpan(
                          text: address.contactPhone,
                          style: TextStyle(color: Colors.grey, fontSize: 14),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 5),
                  Text(
                    address.provCityCounty + address.detailAddress,
                    style: TextStyle(color: Colors.black87),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
              onTap: () => _popResult(context, address),
            ),
          ),
          GestureDetector(
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 12),
              decoration: BoxDecoration(
                border: Border.all(color: Theme.of(context).primaryColor),
                borderRadius: BorderRadius.all(Radius.circular(8)),
              ),
              margin: EdgeInsets.only(left: 12),
              child: Text(
                '编辑',
                style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 12),
              ),
            ),
            onTap: () => _pushAddressEditPage(context, needVerifyCode, address),
          ),
        ],
      ),
    );
  }
}

class _AddressItemNormalWidget extends StatelessWidget {
  final bool needVerifyCode;
  final Address address;
  final bool header;
  final bool footer;

  const _AddressItemNormalWidget({
    Key key,
    @required this.needVerifyCode,
    @required this.address,
    @required this.header,
    @required this.footer,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Slidable(
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: Row(
          children: <Widget>[
            Container(
              margin: EdgeInsets.symmetric(horizontal: 12),
              child: Image.asset('assets/images/order/ic_location.png', width: 16),
            ),
            Expanded(
              child: GestureDetector(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text.rich(
                      TextSpan(
                        text: address.linkMan,
                        style: TextStyle(fontSize: 16),
                        children: [
                          TextSpan(text: '  '),
                          TextSpan(
                            text: address.contactPhone,
                            style: TextStyle(color: Color(0xFF43434D), fontSize: 11),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 5),
                    Text(
                      address.provCityCounty + address.detailAddress,
                      style: TextStyle(color: Colors.black87),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ],
                ),
                onTap: () => _popResult(context, address),
              ),
            ),
            GestureDetector(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                  border: Border.all(color: Theme.of(context).primaryColor),
                  borderRadius: BorderRadius.all(Radius.circular(8)),
                ),
                margin: EdgeInsets.only(left: 12),
                child: Text(
                  '编辑',
                  style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 12),
                ),
              ),
              onTap: () => _pushAddressEditPage(context, needVerifyCode, address),
            ),
          ],
        ),
      ),
      actionPane: SlidableDrawerActionPane(),
      secondaryActions: <Widget>[
        IconSlideAction(
          color: Colors.red,
          icon: Icons.delete,
          onTap: () => _addressDelete(context),
        )
      ],
    );
  }

  void _addressDelete(BuildContext context) async {
    AddressDeleteModel addressDeleteModel = Provider.of(context, listen: false);
    ViewState viewState = await addressDeleteModel.addressDelete(address.id);
    switch (viewState) {
      case ViewState.error:
        EasyLoading.showToast(addressDeleteModel.errorMessage);
        break;
      default:
        EasyLoading.showToast('删除成功');
        AddressListModel addressListModel = Provider.of(context, listen: false);
        addressListModel.refreshData();
        break;
    }
  }
}

void _pushAddressEditPage(BuildContext context, bool needVerifyCode, Address address) async {
  var result = await Navigator.of(context).pushNamed(
    AddressEditPage.routeName,
    arguments: AddressEditPageArgs(needVerifyCode, address),
  );
  if (result is bool ? result : false) {
    AddressListModel addressListModel = Provider.of(context, listen: false);
    addressListModel.refreshData();
  }
}

void _popResult(BuildContext context, Address address) {
  AddressListModel addressListModel = Provider.of(context, listen: false);
  if (addressListModel.selectable) {
    Navigator.of(context).pop(address);
  }
}
